<template>
    <div class="bootstrap-table-container">
      <table ref="table" class="table">
        <thead>
          <tr>
            <th data-field="id">ID</th>
            <th data-field="name">名称</th>
            <th data-field="price">价格</th>
          </tr>
        </thead>
      </table>
    </div>
  </template>
  
  <script>
  import $ from 'jquery'
  import 'jquery-validation'
  import 'bootstrap-table/dist/bootstrap-table.min.css'
  import 'bootstrap-table/dist/bootstrap-table.min.js'
  import 'bootstrap-table/dist/locale/bootstrap-table-zh-CN.min.js'
  import 'jquery-treegrid/js/jquery.treegrid.min.js'
  import 'jquery-treegrid/css/jquery.treegrid.css'
  import { defaultOptions, defaultLocale } from './config'
  
  export default {
    name: 'BootstrapTable',
    props: {
      dataUrl: {
        type: String,
        required: true
      },
      options: {
        type: Object,
        default: () => ({})
      },
      isTreeGrid: {
        type: Boolean,
        default: false
      }
    },
    mounted() {
      this.initTable()
    },
    beforeDestroy() {
      $(this.$refs.table).bootstrapTable('destroy')
    },
    methods: {
      initTable() {
        const treeOptions = this.isTreeGrid ? {
          idField: 'id',
          treeShowField: 'name',
          parentIdField: 'parentId',
          onPostBody: () => {
            const columns = $(this.$refs.table).bootstrapTable('getOptions').columns
            if (columns && columns[0][0].field === 'name') {
              $(this.$refs.table).treegrid({
                treeColumn: 0,
                expanderExpandedClass: 'glyphicon glyphicon-minus',
                expanderCollapsedClass: 'glyphicon glyphicon-plus'
              })
            }
          }
        } : {}
  
        $(this.$refs.table).bootstrapTable({
          ...defaultOptions,
          ...treeOptions,
          ...this.options,
          locale: defaultLocale,
          url: this.dataUrl,
          detailFormatter: this.detailFormatter
        })
      },
      detailFormatter(index, row) {
        return `
          <div class="detail-view">
            <p>ID: ${row.id}</p>
            <p>详细描述: ${row.description || '暂无'}</p>
            <p>创建时间: ${row.createTime || '暂无'}</p>
          </div>
        `
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .bootstrap-table-container {
    padding: 20px;
    
    ::v-deep .table {
      border-collapse: separate;
      border-spacing: 0;
      
      > thead > tr > th {
        background-color: #f5f7fa;
        color: #606266;
        font-weight: 500;
        border-bottom: 1px solid #dcdfe6;
      }
      
      > tbody > tr > td {
        border-bottom: 1px solid #dcdfe6;
      }
  
      .treegrid-expander {
        display: inline-block;
        width: 16px;
        height: 16px;
        cursor: pointer;
        margin-right: 5px;
      }
    }
  }
  
  .detail-view {
    padding: 10px;
    background-color: #f8f9fa;
  }
  </style>